import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { isString, isUndefined } from 'lodash';

/**
 * 请求失败过滤器
 */
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = HttpStatus.OK
    const exceptionResponse = exception.getResponse();
    if (isString(exceptionResponse)) {
      response.status(status).json({
        success: false,
        message: exceptionResponse,
        statusCode: status
      });
    } else if (isUndefined(exceptionResponse['success'])) {
      response.status(status).json({
        success: false,
        statusCode: status,
        ...exceptionResponse
      });
    } else {
      response.status(status).json(exceptionResponse);
    }
  }
}
